<template>
    <!-- 使用 :open 和 @update:open 来替代 v-model -->
    <a-modal :open="open" title="添加学生违纪" @ok="handleOk" @cancel="closeModal" :destroyOnClose="true" :closable="false"
      :maskClosable="false" okText="确认" cancelText="取消">
  
      <a-form ref="formRef" :model="formState" name="dynamic_rule" v-bind="formItemLayout">
        
        <a-form-item label="学号" name="studentNumber" :rules="rules.studentNumber">
          <a-input v-model:value="formState.studentNumber" />
        </a-form-item>
  
        <a-form-item label="违纪情况" name="violationOfDiscipline">
          <a-textarea v-model:value="formState.violationOfDiscipline" />
        </a-form-item>
        <a-form-item label="扣分" name="deductionItem" :rules="rules.deductionItem">
          <a-input v-model:value="formState.deductionItem" />
        </a-form-item>

      </a-form>
    </a-modal>
  </template>
  
  <script setup>
  import { reactive, ref, watch, nextTick } from 'vue';
  import { addBreakTheRule } from '@/api/breakTheRuleApi';
  import { notification } from 'ant-design-vue';
  
  
  
  // 接收父组件传递的 props
  const props = defineProps({
    open: Boolean, // 接收 open 状态
  });
  
  // 触发事件传递给父组件
  const emit = defineEmits(['update:open', 'add']);
  
  const formRef = ref();
  const formState = reactive({
    studentNumber: '',
    violationOfDiscipline:'',
    deductionItem:'',
  });
  
  // 验证规则
  const rules = {
    studentNumber: [{ required: true, message: '学号为必填项，必须是12位数字！', pattern: /^\d{12}$/ }],
    deductionItem: [
    { 
      required: true, 
      message: '扣分项为必填项！' 
    },
    { 
      validator: (rule, value) => {
        if (value < 100) {
          return Promise.resolve();
        } else {
          return Promise.reject(new Error('扣分项必须小于100'));
        }
      },
      trigger: 'blur' // 设置触发验证的事件，比如 "blur" 或 "change"
    }
  ]
  };
  
  const handleOk = async () => {
    try {
  
      const values = await formRef.value.validateFields(); // 验证表单
      Object.assign(formState, values); // 更新 formState
      console.log('Success:', formState);
  
      const res = await addBreakTheRule(formState);
      console.log(res);
  
      emit('add'); // 仅在添加成功后触发
      emit('update:open', false); // 关闭模态框
      notification.success({
        message: '添加成功',
        description: '学生违纪已成功添加。',
      });
  
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
      // 或者在错误处理部分
      notification.error({
        message: '添加失败',
        description: '学生违纪添加失败，请重试。',
      });
    }
  };
  
  // 关闭模态框的事件
  const closeModal = () => {
    emit('update:open', false); // 手动关闭模态框
  };
  
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 8 },
  };
  
  // 监听 props.open 状态变化
  watch(() => props.open, async (newVal) => {
    if (newVal) {
      await nextTick();
      formRef.value.$el.querySelector('input').focus(); // 假设第一个输入框是要聚焦的元素
    } else {
      formRef.value.resetFields(); // 重置表单内容
    }
  });
  </script>
  
  <style scoped>
  /* 样式定义 */
  </style>
  